
//Copyright 1997-2009 Syrinx Development, Inc.
//This file is part of the Syrinx Web Application Framework (SWAF).
// == BEGIN LICENSE ==
//
// Licensed under the terms of any of the following licenses at your
// choice:
//
//  - GNU General Public License Version 3 or later (the "GPL")
//    http://www.gnu.org/licenses/gpl.html
//
//  - GNU Lesser General Public License Version 3 or later (the "LGPL")
//    http://www.gnu.org/licenses/lgpl.html
//
//  - Mozilla Public License Version 1.1 or later (the "MPL")
//    http://www.mozilla.org/MPL/MPL-1.1.html
//
// == END LICENSE ==
using System;
using System.Diagnostics;

using Swaf;
using Swaf.BizRule;

namespace Swaf.Security
{
	/// <summary>
	/// This class provides support for allowing rules to run under a different
	/// security login context than the service exposing the rule.
	/// </summary>

	public class RuleImpersonationDecorator : IRuleDecorator
	{
		protected string m_name;
		protected ISecurityCredential m_credential;
		protected String m_catalogEntry="";
		protected Impersonation m_impersonation;

		public RuleImpersonationDecorator(string name, string val, object extraInfo)
		{
			m_name = name;
			m_catalogEntry = val;
			m_credential = (ISecurityCredential) Application.currentApp.appData.get(val);
		}

		#region IRuleDecorator Members

		public string Value	{get{return m_catalogEntry;}}

		public string Name {get{return m_name;}}

		public object decorateInstance(object theInst)
		{
			return theInst;
		}

		public bool IsStandin {get{return true;}}

		/// <summary>
		/// This call will setup the transaction manager to support the transaction support required by the rule
		/// before the rule is executed.
		/// </summary>
		/// <param name="rule"></param>
		/// <returns>Always returns true because a rule will never not be executed due to transaction issues.</returns>
		public bool preRuleExecution(IRunningRule rule)
		{
			try
			{
				m_impersonation = new Impersonation();
				m_impersonation.ImpersonateUser(m_credential.UserDomain, m_credential.UserId, m_credential.Password);
			}
			catch(Exception e)
			{

			}
			return true;
		}

		/// <summary>
		/// This call will check to see if a transaction is completed based on this
		/// rule being the initial rule that created the transaction
		/// </summary>
		/// <param name="info"></param>
		public void postRuleExecution(IRunningRule rule, ref object ruleReturn, ref Exception ruleException)
		{
			m_impersonation.stopImpersonation();
		}
		#endregion
	}

}